/*
 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * Contributors:
 *     bstefanescu
 */
package org.nuxeo.gwt.habyt.invocation.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;

import org.nuxeo.gwt.habyt.invocation.client.Invocation;
import org.nuxeo.gwt.habyt.invocation.client.InvocationException;
import org.nuxeo.gwt.habyt.invocation.client.InvocationResponse;

/**
 * This handler serves static templates from a templates root directory inside
 * the war. To implement dynamic templates you may extend this class and
 * override the {@link #render(Object,Reader)} method.
 * 
 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
 * 
 */
public class FileInvocationHandler implements InvocationHandler {

    protected String root;

    protected String encoding;

    protected ServletContext ctx;

    public void init(ServletConfig config) {
        root = config.getInitParameter("templates.root");
        if (root == null) {
            root = "/templates";
        }
        encoding = config.getInitParameter("templates.encoding");
        if (encoding == null) {
            encoding = "UTF-8";
        }
        ctx = config.getServletContext();
    }

    protected String getContent(Object target, String name) throws Exception {
        InputStream in = ctx.getResourceAsStream(root + "/" + name);
        if (in != null) {
            Reader reader = new InputStreamReader(in, encoding);
            try {
                return render(target, reader);
            } finally {
                reader.close();
            }
        }
        throw new InvocationException("No such template: " + name);
    }

    /**
     * Override this method to provide dynamic templates
     * 
     * @param context
     * @param reader
     * @return
     * @throws Exception
     */
    protected String render(Object context, Reader reader) throws Exception {
        // context objects are not supported in this implementation
        return readFully(reader);
    }

    @Override
    public void invoke(Invocation invocation, InvocationResponse response)
            throws InvocationException {
        try {
            String content = getContent(invocation.getContent(),
                    invocation.getTarget().getId());
            response.setContent(content);
        } catch (InvocationException e) {
            throw e;
        } catch (Exception e) {
            throw new InvocationException("Failed to read template: "
                    + invocation.getTarget().getId(), e);
        }
    }

    public static String readFully(Reader in) throws IOException {
        StringBuilder sb = new StringBuilder(1024 * 64);
        char[] buffer = new char[1024 * 64];
        try {
            int read;
            while ((read = in.read(buffer)) != -1) {
                sb.append(buffer, 0, read);
            }
        } finally {
            in.close();
        }
        return sb.toString();
    }

}
